#include "QcPickWorkspace.h"
#include <QPainter>
#include <QDragEnterEvent>
#include <QDropEvent>
#include <QMimeData>
#include <QUrl>
#include <QDir>
#include <QFileDialog>
#include <QFileIconProvider>
#include "util/QuFile.h"

void QcPickWorkspace::paintEvent(QPaintEvent *e)
{
    super_::paintEvent(e);

    // TODO: 无法正常显示提示信息
    if (super_::count() == 0) {
        QPainter painter(this);
        painter.drawText(0, 0, "双击或拖拽添加扫描路径");
    }
}

namespace kPrivate
{
    static bool isLocalDirs(const QList<QUrl>& urls)
    {
        for (auto& url : urls) {
            if (!url.isLocalFile() || !QDir(url.toLocalFile()).exists())
                return false;
        }

        return true;
    }
}


void QcPickWorkspace::QcPickWorkspace::dragEnterEvent(QDragEnterEvent *e)
{
    if (e->mimeData()->hasUrls() && kPrivate::isLocalDirs(e->mimeData()->urls()))
        e->accept();
}


void QcPickWorkspace::dragMoveEvent(QDragMoveEvent *e)
{
    e->accept();
}

void QcPickWorkspace::dropEvent(QDropEvent *e)
{
    for (auto& url : e->mimeData()->urls()) {
        if (url.isLocalFile() && QDir(url.toLocalFile()).exists())
            addPath(url.toLocalFile());
    }
}

void QcPickWorkspace::mouseDoubleClickEvent(QMouseEvent *e)
{
    super_::mouseDoubleClickEvent(e);

    if (!this->itemAt(e->pos())) // 点击空白处，触发目录对话框，新增扫描路径
        on_new_path();
}

void QcPickWorkspace::addPath(const QString& path)
{
    addItem(new QListWidgetItem(QFileIconProvider().icon(QFileInfo(path)), path));
}

void QcPickWorkspace::on_new_path()
{
    QString path = QFileDialog::getExistingDirectory();
    if (!path.isEmpty())
        addPath(path);
}

void QcPickWorkspace::on_remove_path()
{
    auto rowIdx = currentRow();
    if (rowIdx >= 0)
        delete takeItem(rowIdx);
}

void QcPickWorkspace::on_open_path()
{
    auto rowIdx = currentRow();
    if (rowIdx >= 0)
        QuFile::shellOpen(item(rowIdx)->text());
}
